const { query } = require('../config/db');

class User {
  /**
   * 根据openid查找用户
   * @param {string} openid - 微信用户唯一标识
   * @returns {Promise<Object|null>} 用户信息
   */
  static async findByOpenid(openid) {
    try {
      const users = await query(
        'SELECT * FROM users WHERE openid = ?',
        [openid]
      );
      return users.length > 0 ? users[0] : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID查找用户
   * @param {number} id - 用户ID
   * @returns {Promise<Object|null>} 用户信息
   */
  static async findById(id) {
    try {
      const users = await query(
        'SELECT * FROM users WHERE id = ?',
        [id]
      );
      return users.length > 0 ? users[0] : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  /**
   * 创建新用户
   * @param {Object} userData - 用户数据
   * @returns {Promise<Object>} 创建的用户信息
   */
  static async create(userData) {
    try {
      const { openid, unionid, nickname, avatar_url, phone_number } = userData;
      
      const result = await query(
        `INSERT INTO users (openid, unionid, nickname, avatar_url, phone_number, last_login_at) 
         VALUES (?, ?, ?, ?, ?, NOW())`,
        [openid, unionid, nickname, avatar_url, phone_number]
      );

      return await this.findById(result.insertId);
    } catch (error) {
      console.error('创建用户失败:', error);
      throw error;
    }
  }

  /**
   * 更新用户信息
   * @param {number} id - 用户ID
   * @param {Object} updateData - 更新数据
   * @returns {Promise<Object>} 更新后的用户信息
   */
  static async update(id, updateData) {
    try {
      const fields = [];
      const values = [];

      Object.keys(updateData).forEach(key => {
        if (updateData[key] !== undefined) {
          fields.push(`${key} = ?`);
          values.push(updateData[key]);
        }
      });

      if (fields.length === 0) {
        throw new Error('没有要更新的字段');
      }

      values.push(id);
      await query(
        `UPDATE users SET ${fields.join(', ')} WHERE id = ?`,
        values
      );

      return await this.findById(id);
    } catch (error) {
      console.error('更新用户失败:', error);
      throw error;
    }
  }

  /**
   * 更新最后登录时间
   * @param {number} id - 用户ID
   * @returns {Promise<void>}
   */
  static async updateLastLogin(id) {
    try {
      await query(
        'UPDATE users SET last_login_at = NOW() WHERE id = ?',
        [id]
      );
    } catch (error) {
      console.error('更新登录时间失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户列表（分页）
   * @param {number} page - 页码
   * @param {number} pageSize - 每页大小
   * @param {string} search - 搜索关键词
   * @returns {Promise<Object>} 用户列表和总数
   */
  static async getList(page = 1, pageSize = 10, search = '') {
    try {
      const safePage = Math.max(1, parseInt(page) || 1);
      const safePageSize = Math.max(1, parseInt(pageSize) || 10);
      const offset = (safePage - 1) * safePageSize;

      let whereClause = '';
      let params = [];

      if (search && String(search).trim()) {
        whereClause = 'WHERE nickname LIKE ? OR phone_number LIKE ?';
        const searchTerm = `%${String(search).trim()}%`;
        params = [searchTerm, searchTerm];
      }

      // 获取总数
      const countResult = await query(
        `SELECT COUNT(*) as total FROM users ${whereClause}`,
        params
      );
      const total = countResult[0].total;

      // 获取列表
      const users = await query(
        `SELECT id, openid, nickname, avatar_url, phone_number, last_login_at, created_at
         FROM users ${whereClause}
         ORDER BY created_at DESC
         LIMIT ${safePageSize} OFFSET ${offset}`,
        params
      );

      return { users, total };
    } catch (error) {
      console.error('获取用户列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户统计数据
   * @returns {Promise<Object>} 统计数据
   */
  static async getStats() {
    try {
      // 总用户数
      const totalResult = await query('SELECT COUNT(*) as total FROM users');
      const total = totalResult[0].total;

      // 今日新增用户数
      const todayResult = await query(
        'SELECT COUNT(*) as today FROM users WHERE DATE(created_at) = CURDATE()'
      );
      const today = todayResult[0].today;

      // 昨日新增用户数
      const yesterdayResult = await query(
        'SELECT COUNT(*) as yesterday FROM users WHERE DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)'
      );
      const yesterday = yesterdayResult[0].yesterday;

      // 本月新增用户数
      const thisMonthResult = await query(
        'SELECT COUNT(*) as thisMonth FROM users WHERE YEAR(created_at) = YEAR(NOW()) AND MONTH(created_at) = MONTH(NOW())'
      );
      const thisMonth = thisMonthResult[0].thisMonth;

      return {
        total,
        today,
        yesterday,
        thisMonth
      };
    } catch (error) {
      console.error('获取用户统计失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户增长趋势（最近7天）
   * @returns {Promise<Array>} 趋势数据
   */
  static async getGrowthTrend() {
    try {
      const result = await query(`
        SELECT 
          DATE(created_at) as date,
          COUNT(*) as count
        FROM users 
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        GROUP BY DATE(created_at)
        ORDER BY date ASC
      `);

      return result;
    } catch (error) {
      console.error('获取用户增长趋势失败:', error);
      throw error;
    }
  }
}

module.exports = User;
